﻿using UnityEngine;
using UnityEngine.UI;
using System.Linq;
using System.IO;
using System.Collections;

public class Cam : MonoBehaviour {

	WebCamTexture wct;
	public RawImage avatarImageTexture;
	public Renderer faceMappingPlane;

	Texture2D testPhoto;


	void Start () {

		if (Application.isEditor) {
			testPhoto = new Texture2D (1280, 960);
			string testPhotoPath = Path.Combine (Path.Combine (Application.dataPath, "Resources"), "TestPhoto.jpg");
			byte[] fileData = File.ReadAllBytes (testPhotoPath);
			testPhoto.LoadImage (fileData);
		}

		wct = new WebCamTexture( WebCamTexture.devices.Last().name , Screen.height, Screen.width, 12);

		if (Application.isEditor) {
			faceMappingPlane.material.mainTexture = testPhoto;
		} else {
			faceMappingPlane.material.mainTexture = wct;
		}

		wct.Play();
	}
		

	public void CutOutFace() {

		wct.Pause(); 

		Texture2D cam_image = new Texture2D (1280, 960);

		// 如果是开发环境，就载入测试照片
		if (Application.isEditor) {
			cam_image = testPhoto;
		} else {
			cam_image.SetPixels (wct.GetPixels ());
			cam_image.Apply ();
		}

		// 切 x:398 y:187 width:700 height:600 的内容
		Texture2D image = new Texture2D( 700 , 600 , TextureFormat.ARGB32 , false );
		image.SetPixels ( cam_image.GetPixels( 398,187,700,600) );
		image.Apply();

		avatarImageTexture.material.mainTexture = image;

		// 开发版本时，保存到 Avatar.png
		if( Application.isEditor ) {
			string avatarPath = Path.Combine (Path.Combine (Application.dataPath, "Resources"), "Avatar.png");
			File.WriteAllBytes ( avatarPath , image.EncodeToPNG() );
		}

	}


}
